/**
 * 本地化的一些类，用于对文件的一些操作
 * 
 * 
 * 
 * */
package cn.edu.scau.liangshanhero.localization;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import cn.edu.scau.liangshanhero.util.FileUtilImpl;
import cn.edu.scau.liangshanhero.util.Messages;
import cn.edu.scau.liangshanhero.util.Unicode2UTF8;

public class ChinezationUtil {
	static Vector<File> allFilesWithExtends = new Vector<File>();

	// 将所有的属性文件中的英语单词放入这个Map中

	public static Map<String, String> putAllPropertiesFileEnglishWord2Map(Vector<File> sourceFileVector,
			List<File> propertiesFileList, String propertiesDirectory) {
		Map<String, String> propertiesEnglishChineseMap = new HashMap();
		Iterator<File> propertiesFileListIterator = propertiesFileList.iterator();
		
		while (propertiesFileListIterator.hasNext()) {
			File sourcePropertieFile = propertiesFileListIterator.next();
			sourceFileVector.add(sourcePropertieFile);
			Set<String> keys = new HashSet<String>();
//			把所有的单词put到
			putWord2KeySet(sourcePropertieFile, keys);
			// 获取所有的已经存在的映射
			Map<String, String> existWordMap = ChinezationUtil.getExistedEnglish2ChineseMap(propertiesDirectory.toString());
			Iterator<String> keyIterator = keys.iterator();
			while (keyIterator.hasNext()) {
				String key = keyIterator.next();
				propertiesEnglishChineseMap.put(key, existWordMap.get(key));// 写入到映射集合中，值为从现有的map文件获取。
			}
			
		}
		return propertiesEnglishChineseMap;
	}

	@SuppressWarnings("resource")
	public static void putWord2KeySet(File sourcePropertieFile, Set<String> keys) {
		String sourcePropertiesLine;
		try {
			BufferedReader sourcePropertiesLineBufferedReader;
			sourcePropertiesLineBufferedReader = new BufferedReader(new FileReader(sourcePropertieFile));
			while ((sourcePropertiesLine = sourcePropertiesLineBufferedReader.readLine()) != null) {
				// 如果本行为空，就跳过
				if (sourcePropertiesLine.indexOf("=") != -1) { //$NON-NLS-1$
					// 截取单词,先看是否有多个单词
					if (sourcePropertiesLine.substring(sourcePropertiesLine.indexOf("=")).indexOf(" ") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
						// 如果有多个单词，就应该分拆
						String[] wordsPerLine = new String[10];// 每一行的单词个数，应该不会超过10个
						wordsPerLine = sourcePropertiesLine.substring(sourcePropertiesLine.indexOf("=") + 1).split(" "); //$NON-NLS-1$
						for (int i = 0; i < wordsPerLine.length; i++) {
							keys.add(wordsPerLine[i]);
						}
					} else
						keys.add(sourcePropertiesLine.substring(sourcePropertiesLine.indexOf("=") + 1).toString());
				}
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// 将所有的国际化文件创建本地化属性文件，该方法暂时没
	public static void createTargerPropertiesFile(File sourceFile,	File targetFile, Map<String, String> word2ChineseMap) {
		String line = ""; //$NON-NLS-1$
		try {
			FileReader reader = new FileReader(sourceFile);
			FileWriter writer = new FileWriter(targetFile);
			BufferedReader br = new BufferedReader(reader);
			BufferedWriter bw = new BufferedWriter(writer);
			while ((line = br.readLine()) != null) {
				// 如果没有等号，就表示不需要替换，例如注释就不需要
				if (line.indexOf("=") != -1) { //$NON-NLS-1$
					line = replaceWord2ChineseByMapPerLine(line, word2ChineseMap);
				}
				bw.write(line);
				bw.newLine();
				bw.flush();
			}
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 将属性文件的每一行中的英语单词替换成为map文件中的中文
	private static String replaceWord2ChineseByMapPerLine(String line,	Map<String, String> englist2ChineseMap) {
		// System.out.println("本行还没有转成中文之前的内容是：" + line);
		Set<String> words = new HashSet<String>();// 每一行的单词集合
		if (line.indexOf("=") != -1) {// 如果本行为空或者是注释，就跳过// 截取单词,先看是否有多个单词 //$NON-NLS-1$
			if (line.substring(line.indexOf("=")).indexOf(" ") != -1) {// 多个单词 //$NON-NLS-1$ //$NON-NLS-2$
				String[] wordsPerLine = line.substring(line.indexOf("=") + 1).split(" "); //$NON-NLS-1$
				for (int i = 0; i < wordsPerLine.length; i++) {
					words.add(wordsPerLine[i]);
				}
			} else
				// 单个单词
				words.add(line.substring(line.indexOf("=") + 1).toString()); //$NON-NLS-1$
		}
		// System.out.println("本行的单词是：" + words);
		// 替换本行中所有的单词
		Iterator<String> wordsIterator = words.iterator();
		String preLine = line.substring(0, line.indexOf("=")); //$NON-NLS-1$
		String postLine = line.substring(line.indexOf("=") + 1); //$NON-NLS-1$
		while (wordsIterator.hasNext()) {
			String word = (String) wordsIterator.next();
			postLine = postLine.replaceAll(word, englist2ChineseMap.get(word));
		}
		postLine = postLine.replaceAll(" ", "");// 去掉中文之间的空格 //$NON-NLS-1$ //$NON-NLS-2$
		// 将postLine转为UTF-8字符集
		postLine = Unicode2UTF8.utf8ToUnicode(postLine);
		return preLine + "=" + postLine; //$NON-NLS-1$
	}

	/** 从map文件中获取所有的已经存在的英语单词，如果该文件不存在，就创建，供本次保存以及下次使用 */

	public static Map<String, String> getExistedEnglish2ChineseMap(String propertiesDirectory) {
		Map<String, String> existedEnglish2ChineseMap = new HashMap<String, String>();
		try {
			String sourceFilePath = propertiesDirectory +"properties.map";
			System.out.println("properties.map文件是："+sourceFilePath);
			File sourceFile = new File(sourceFilePath);
			if (!sourceFile.exists()) {
				try {
					sourceFile.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			FileReader reader = new FileReader(sourceFile);
			BufferedReader br = new BufferedReader(reader);
			String line = ""; //$NON-NLS-1$
			while ((line = br.readLine()) != null) {
				System.out.println(line);
				String key = line.split("=")[0]; //$NON-NLS-1$
				String value = ""; //$NON-NLS-1$
				if (line.split("=").length > 1) { //$NON-NLS-1$
					value = line.split("=")[1]; //$NON-NLS-1$
				}
				existedEnglish2ChineseMap.put(key, value);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return existedEnglish2ChineseMap;

	}

	// 获取指定目录下所有的“非”本地化的properties文件列表，即不是zh_CN.properties的文件
	public static List<File> getSourcePropertiesFileList(File propertiesFileDirectory) {// 扫描.properties后缀文件
		
		List<File> propertiesFileList = new ArrayList<File>();
		File[] propertiesFiles = propertiesFileDirectory
				.listFiles(FileUtilImpl.getFileExtensionFilter(".properties")); //$NON-NLS-1$
		for (int i = 0; i < propertiesFiles.length; i++) {
			CharSequence s = "zh_CN"; //$NON-NLS-1$
			if (!propertiesFiles[i].toString().contains(s)) {
				propertiesFileList.add(propertiesFiles[i]);
			}
		}
		return propertiesFileList;
	}

	

	// 生成所有的目的文件
	public static void createTargetPropertiesFiles(
			final Vector<File> sourceFileVector,
			final Map<String, String> english2ChineseMap,
			final String propertiesDirectory, Composite localizationComposite) {
		final Set<?> english2ChineseSet = english2ChineseMap.entrySet();// 单词2中文的映射中的英语单词的集合

		final Text[] english = new Text[english2ChineseSet.size()];
		final Text[] chinese = new Text[english2ChineseSet.size()];
		int wordIndex = 0;// 单词数组的下标

		final Table table = new Table(localizationComposite, SWT.MULTI | SWT.BORDER);
		table.setSize(400, 1000);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		TableColumn tableColumn0 = new TableColumn(table, SWT.CENTER);
		tableColumn0.setWidth(200);
		tableColumn0.setText(Messages.FileUtil_0);
		TableColumn tableColumn1 = new TableColumn(table, SWT.CENTER);
		tableColumn1.setWidth(400);
		tableColumn1.setText(Messages.FileUtil_23);

		Iterator<?> word2ChineseSet4TableIterator = english2ChineseSet
				.iterator();

		while (word2ChineseSet4TableIterator.hasNext()) {
			Entry<?, ?> word2ChineseEntry = (Entry<?, ?>) word2ChineseSet4TableIterator
					.next();
			word2ChineseEntry.getKey();// 英语单词
			word2ChineseEntry.getValue();// 英语单词的中文

			TableItem tableItem = new TableItem(table, SWT.NONE);

			english[wordIndex] = new Text(table, SWT.NONE);
			english[wordIndex].setText(word2ChineseEntry.getKey().toString());

			tableItem.setText(0, english[wordIndex].getText().toString());

			chinese[wordIndex] = new Text(table, SWT.NONE);
			chinese[wordIndex]
					.setText((word2ChineseEntry.getValue() == null) ? "" //$NON-NLS-1$
							: word2ChineseEntry.getValue().toString());
			TableEditor tableEditor = new TableEditor(table);
			tableEditor.grabHorizontal = true;
			tableEditor.setEditor(chinese[wordIndex], tableItem, 1);// 第二列显示输入中文
			wordIndex++;
		}
		
		Button btn = new Button(localizationComposite, SWT.NONE);
		btn.setBounds(30, 40, 50, 80);
		btn.setText(Messages.FileUtil_25);
		btn.addMouseListener(new MouseListener() {
			@Override
			public void mouseDoubleClick(MouseEvent arg0) {
			}

			@Override
			public void mouseDown(MouseEvent arg0) {
			}

			@Override
			public void mouseUp(MouseEvent arg0) {
				// 在这里添加鼠标单击后的相关操作 //生成映射
				for (int i = 0; i < english2ChineseSet.size(); i++) {
					english2ChineseMap.put(english[i].getText(),
							chinese[i].getText());
				}
				Iterator<File> sourceFileVectorIterator = sourceFileVector
						.iterator();
				// 调用本地函数，依次生成所有的目标文件
				while (sourceFileVectorIterator.hasNext()) {
					File sourceFile = sourceFileVectorIterator.next();
					String sourceFilePath = sourceFile.getAbsolutePath();
					String targetFilePath = sourceFilePath.replace(
							"resources.properties", //$NON-NLS-1$
							"resources_zh_CN.properties"); //$NON-NLS-1$
					File targetFile = new File(targetFilePath);
					// 调用本地方法替换掉本地化属性文件中的所有=符号之后的有映射的英语
					ChinezationUtil.createTargerPropertiesFile(sourceFile,
							targetFile, english2ChineseMap);// 将每一个源文件生成本地化文件
				}
				// 将Map写入到map文件中
				Set<?> word2ChineseSet = english2ChineseMap.entrySet();
				Iterator<?> word2ChineseSetIterator = word2ChineseSet
						.iterator();

				String propertiesMapFile = propertiesDirectory
						+ "\\properties.map"; //$NON-NLS-1$
				FileWriter writer;
				try {
					writer = new FileWriter(propertiesMapFile);
					BufferedWriter bw = new BufferedWriter(writer);
					while (word2ChineseSetIterator.hasNext()) {
						Entry<?, ?> word2ChineseEntry = (Entry<?, ?>) word2ChineseSetIterator
								.next();
						word2ChineseEntry.getKey();// 英语单词
						word2ChineseEntry.getValue();// 英语单词的中文
						if (word2ChineseEntry.getValue() != null) {// 如果中文不为空
							String line = word2ChineseEntry.getKey().toString()
									+ "=" //$NON-NLS-1$
									+ word2ChineseEntry.getValue().toString();
							bw.write(line);
							bw.newLine();
							bw.flush();
						}
					}
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		table.setTopIndex(1);
		localizationComposite.setToolTipText(" 映射设置界面... ");
		localizationComposite.pack();
//		shell.open();
		while (!localizationComposite.isDisposed()) {
			if (!Display.getDefault().readAndDispatch()) {
				Display.getDefault().sleep();
			}

		}
		Display.getDefault().dispose();

	}

	
	
}